<template>
  <div class='commentList'>
    <van-cell>
      <div slot="title">全部评论</div>
    </van-cell>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <comment-item
        v-for="(comments, index) in commentList"
        :key="index"
        :comments="comments"
        @update-reply="$emit('update-reply', $event)"
      />
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comments.js'
import commentItem from './comment-item'

export default {
  name: 'commentList',
  components: {
    commentItem
  },
  props: {
    source: {
      type: [Object, Number, String],
      required: true
    },
    commentList: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      default: 'a'
    }
  },
  data () {
    return {
      // commentList: [], // 从服务器拿到的评论数据
      loading: false, // 是否加载
      finished: false, // 加载是否完成
      offset: null, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
      limit: 10 // 获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
    }
  },
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      const { data } = await getComments({
        type: this.type, // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
        source: this.source, // 源id，文章id或评论id
        offset: this.offset,
        limit: this.limit
      })
      this.$emit('commentNumber', data.data.total_count)
      const { results } = data.data
      this.commentList.push(...results)
      this.loading = false
      if (results.length) {
        this.offset = data.data.last_id
      } else {
        this.finished = true
      }
    }
  }
}
</script>
<style lang='less' scoped></style>
